package com.learn.jdk;

import java.util.concurrent.RecursiveTask;

/**
 * 定义计算数组和的拆分任务(分治)
 * @author: lipan
 * @date: 2021/5/15 11:49
 */

public class AccumlatorRecursizeTask extends RecursiveTask<Integer> {


    private final  int start;

    private final  int end;

    private final int[] data;

    private final int LIMIT=3;

    public AccumlatorRecursizeTask(int start, int end, int[] data) {
        this.start = start;
        this.end = end;
        this.data = data;
    }

    @Override
    protected Integer compute() {

        int result=0;
        if (end-start<=LIMIT){
            for(int i=start;i<end;i++){
                result+=data[i];
            }

            return result;
        }

        System.out.println(Thread.currentThread().getName()+"\t"+start+"\t"+end);

        int mid=(start+end)/2;

        AccumlatorRecursizeTask leftTask=new AccumlatorRecursizeTask(start,mid,data);
        AccumlatorRecursizeTask rightTask=new AccumlatorRecursizeTask(mid,end,data);

           //方式一
//        leftTask.fork();
//        rightTask.fork();

        //方式二
        invokeAll(leftTask,rightTask);

        return  leftTask.join()+rightTask.join();
    }
}
